# -*- coding: utf-8 -*-
import copy
import scrapy
from datetime import datetime
from scrapy.exceptions import IgnoreRequest
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.http_util import retry_request
from cdt.rules import parse_order_item, parse_order
from cdt.utils.converter_pool import ConverterPool
from cdt.utils.login import SeleniumLogin
from zc_core.spiders.base import BaseSpider


class OrderSpider(BaseSpider):
    name = 'order'

    # 常用链接
    api_url = 'http://tang.cdt-ec.com/import-batch/evt/dispatch'
    bill_status = ['4', '5', '6']

    def __init__(self, batchNo=None, *args, **kwargs):
        super(OrderSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        if not batchNo:
            self.batch_no = time_to_batch_no(datetime.now())
        else:
            self.batch_no = int(batchNo)
        self.converter = ConverterPool()

    def start_requests(self):
        cookies = SeleniumLogin().get_cookies()
        # cookies = {
        #     "JSESSIONID": "806B5E63486E4854BB7F982A7C947B97",
        #     "acw_tc": "2760826316224478001334093e4ebbfb46915ee5c76771869ee0d2f1908196",
        #     "yht_username": "ST-691898-vptx3OnPnzC9BrzlZB6T-euc.yonyoucloud.com__eb50f35e-e9ed-4f16-bdb4-5d02909177d8",
        #     "yht_usertoken": "hJQ3%2Fqw5nlEQHVENCWbGbGf%2F2piPIIrHhZjS5XedaBxU5zm0EHfEOZqMST1GCg9BhDlolOfPbOk2rmwRxgxvRQ%3D%3D",
        #     "yht_tenantinfo": "nl9dpvts",
        #     "_TH_": "primary",
        #     "_A_P_userId": "eb50f35e-e9ed-4f16-bdb4-5d02909177d8",
        #     "ucuserid": "eb50f35e-e9ed-4f16-bdb4-5d02909177d8",
        #     "_A_P_userType": "0",
        #     "_A_P_userLoginName": "bjxygly9",
        #     "_A_P_userAvator": "\"\"",
        #     "_A_P_userName": "%25E8%25B5%25B5%25E7%25A3%258A",
        #     "token": "d2ViLDM2MDAsc0x5M3dwcHNCY2dqbXROKzBvbVNtRDlpc2JOQVBBelc3S1hVRGQ5NmV5UFNFeFlTcUdqVDlteGhpbDM2VEtnWitIc0RHb1hLQnRTVXlVeTEvSCtYanc9PQ",
        #     "u_usercode": "eb50f35e-e9ed-4f16-bdb4-5d02909177d8",
        #     "u_logints": "1622448055592",
        #     "logoImgUrl": "./logo.png",
        #     "sysid": "ipu_datang",
        #     "tenantid": "nl9dpvts",
        #     "businessid": "ipu_datang",
        #     "userType": "0",
        #     "u_locale": "zh_CN",
        #     "userId": "eb50f35e-e9ed-4f16-bdb4-5d02909177d8",
        #     "i18next": "zh_CN"
        # }

        # cookies = {'_TH_': 'primary', '_A_P_userName': '%25E8%25B5%25B5%25E7%25A3%258A', 'yht_usertoken': 'ZvBUouwF8DuGN4FpHYc0kbobgcoQmZqNIHWA0EE4CJ8tSb2IokzWZ1RtV9z5ZYpDSg%2B3uJsaT9PZxS%2B5OU1IZg%3D%3D', 'JSESSIONID': '37E11B2E66026ECD6E644A51D6CB33F8', 'acw_tc': '2760827c15813456916475125ed3eb7d6632c74e97fcb85ddd1fc65cbfbcc8', '_A_P_userId': 'eb50f35e-e9ed-4f16-bdb4-5d02909177d8', 'yht_username': 'ST-1532533-SQlWz36hDtdj1F5PqK1T-cas01.example.org__eb50f35e-e9ed-4f16-bdb4-5d02909177d8', 'yht_tenantinfo': 'nl9dpvts', 'ucuserid': 'eb50f35e-e9ed-4f16-bdb4-5d02909177d8', '_A_P_userType': '0', 'userType': '0', 'logoImgUrl': './logo.png', '_A_P_userLoginName': 'bjxygly9', '_A_P_userAvator': '""', 'token': 'd2ViLDM2MDAsSXZEZkJNVThrTlhpVjJUTFFpaEhRSTFJeW01VlJvY2pSL0JyczlFRTNmUWR2WFNlVnZEVVN1ekJkSlUvdktTb1k2RGVFaDRaN1VROEpYSjM5Nk9IYnc9PQ', 'u_usercode': 'eb50f35e-e9ed-4f16-bdb4-5d02909177d8', 'u_logints': '1581345691967', 'sysid': 'ipu_datang', 'tenantid': 'nl9dpvts', 'businessid': 'ipu_datang', 'userId': 'eb50f35e-e9ed-4f16-bdb4-5d02909177d8', 'u_locale': 'zh_CN', 'i18next': 'zh_CN'}
        if not cookies:
            self.logger.error('init cookie failed...')
            return
        self.logger.info('init cookie: %s', cookies)

        page = 0
        for status in self.bill_status:
            yield scrapy.FormRequest(
                method='POST',
                url=self.api_url,
                formdata={
                    'ctrl': 'portal.MiddlemanPurOrderController',
                    'method': 'loadPurData',
                    'environment': '{"clientAttributes":{}}',
                    'dataTables': '{"middlemanPurOrderDataTable":{"meta":{"id":{"enable":true,"required":false,"descs":{}},"subject":{"enable":true,"required":false,"descs":{}},"orderDesc":{"enable":true,"required":false,"descs":{}},"orderno":{"enable":true,"required":false,"descs":{}},"orderOtherId":{"enable":true,"required":false,"descs":{}},"orderTime":{"enable":true,"required":false,"descs":{},"type":"date"},"corpAccount":{"enable":true,"required":false,"descs":{}},"corpSubAccount":{"enable":true,"required":false,"descs":{}},"supplierName":{"enable":true,"required":false,"descs":{}},"totalMoney":{"enable":true,"required":false,"descs":{}},"orderStatus":{"enable":true,"required":false,"descs":{}},"OrderStatusName":{"enable":true,"required":false,"descs":{}},"gmtCreate":{"enable":true,"required":false,"descs":{},"type":"datetime"},"releaseStart":{"enable":true,"required":false,"descs":{},"type":"datetime"},"releaseEnd":{"enable":true,"required":false,"descs":{},"type":"datetime"},"supEnterpriseName":{"enable":true,"required":false,"descs":{}},"erpProductVersion":{"enable":true,"required":false,"descs":{}},"saleOrderDetailInfo":{"enable":true,"required":false,"descs":{}},"purEnterpriseName":{"enable":true,"required":false,"descs":{}},"deliveryStatus":{"enable":true,"required":false,"descs":{}},"orgName":{"enable":true,"required":false,"descs":{}},"EnterpriseName":{"enable":true,"required":false,"descs":{}},"nyAgreementName":{"enable":true,"required":false,"descs":{}},"nyMiddlemanName":{"enable":true,"required":false,"descs":{}},"nySalesModel":{"enable":true,"required":false,"descs":{}},"enterpriseId":{"enable":true,"required":false,"descs":{}},"field1":{"enable":true,"required":false,"descs":{}}},"params":{"cls":"com.yonyou.cpu.domain.middleman.MiddlemanPurOrder"},"rows":[],"select":[0],"focus":-1,"pageSize":100,"pageIndex":' + str(
                        page) + ',"isChanged":false,"master":"","pageCache":false}}',
                    'compression': 'false',
                    'compressType': '',
                    'parameters': '{"billStatus":' + status + ',"pageIndex":' + str(
                        page) + ',"pageSize":100,"queryData":{}}',
                },
                meta={
                    'batchNo': self.batch_no,
                    'status': status,
                    'page': page,
                },
                cookies=cookies,
                callback=self.parse_order,
                errback=self.error_back,
                priority=10,
                dont_filter=True
            )

    def parse_order(self, response):
        meta = response.meta
        page = meta.get('page')
        status = meta.get('status')

        order_list = parse_order(response)
        if order_list and len(order_list):
            self.logger.info('列表: status=%s, page=%s, count=%s]' % (status, page, len(order_list)))
            for order in order_list:
                sp_id = order.get('supplierId')
                if self.converter.contains_supplier(sp_id):
                    yield order

                    # 订单详情
                    id = order.get('id', '')
                    if id:
                        yield scrapy.FormRequest(
                            method='POST',
                            url=self.api_url,
                            formdata={
                                'ctrl': 'portal.MiddlemanPurOrderController',
                                'method': 'findSaleOrderDetailById',
                                'environment': '{"clientAttributes":{}}',
                                'dataTables': '{"middlemanPurOrderDataTable":{"meta":{"id":{"enable":true,"required":false,"descs":{}},"subject":{"enable":true,"required":false,"descs":{}},"orderOtherId":{"enable":true,"required":false,"descs":{}},"orderno":{"enable":true,"required":false,"descs":{}},"orderTime":{"enable":true,"required":false,"descs":{},"type":"datetime"},"corpAccount":{"enable":true,"required":false,"descs":{}},"corpSubAccount":{"enable":true,"required":false,"descs":{}},"supplierName":{"enable":true,"required":false,"descs":{}},"purchaseName":{"enable":true,"required":false,"descs":{}},"notaxMoney":{"enable":true,"required":false,"descs":{}},"totalMoney":{"enable":true,"required":false,"descs":{}},"confirmTotalMoney":{"enable":true,"required":false,"descs":{}},"orderStatus":{"enable":true,"required":false,"descs":{}},"gmtCreate":{"enable":true,"required":false,"descs":{},"type":"datetime"},"releaseStart":{"enable":true,"required":false,"descs":{},"type":"datetime"},"releaseEnd":{"enable":true,"required":false,"descs":{},"type":"datetime"},"purchasePhone":{"enable":true,"required":false,"descs":{}},"supplyPhone":{"enable":true,"required":false,"descs":{}},"supplyPersionName":{"enable":true,"required":false,"descs":{}},"purEnterpriseName":{"enable":true,"required":false,"descs":{}},"supEnterpriseName":{"enable":true,"required":false,"descs":{}},"sendErpMsg":{"enable":true,"required":false,"descs":{}},"purEnterpriseId":{"enable":true,"required":false,"descs":{}},"purOrderId":{"enable":true,"required":false,"descs":{}},"orderSourceId":{"enable":true,"required":false,"descs":{}},"orderSource":{"enable":true,"required":false,"descs":{}},"enterpriseId":{"enable":true,"required":false,"descs":{}},"enterpriseName":{"enable":true,"required":false,"descs":{}},"purchaser_info":{"enable":true,"required":false,"descs":{}},"consignee_info":{"enable":true,"required":false,"descs":{}},"orgName":{"enable":true,"required":false,"descs":{}},"nyRemarks":{"enable":true,"required":false,"descs":{}},"memo":{"enable":true,"required":false,"descs":{}}},"params":{"cls":"com.yonyou.cpu.domain.middleman.MiddlemanPurOrder"},"rows":[],"select":[],"focus":-1,"pageSize":100,"pageIndex":0,"isChanged":false,"master":"","pageCache":false},"middlemanPurOrderDetailDataTable":{"meta":{"id":{"enable":true,"required":false,"descs":{}},"productName":{"enable":true,"required":false,"descs":{}},"amount":{"enable":true,"required":false,"descs":{}},"confirmAmount":{"enable":true,"required":false,"descs":{}},"unit":{"enable":true,"required":false,"descs":{}},"price":{"enable":true,"required":false,"descs":{}},"taxPrice":{"enable":true,"required":false,"descs":{}},"confirmPrice":{"enable":true,"required":false,"descs":{}},"quantity":{"enable":true,"required":false,"descs":{}},"confirmQuantity":{"enable":true,"required":false,"descs":{}},"productDescribe":{"enable":true,"required":false,"descs":{}},"taxrate":{"enable":true,"required":false,"descs":{}},"pricedecidetailid":{"enable":true,"required":false,"descs":{}},"deliverEnterprise":{"enable":true,"required":false,"descs":{}},"deliverAddress":{"enable":true,"required":false,"descs":{}},"recvstor":{"enable":true,"required":false,"descs":{}},"balanceEnterprise":{"enable":true,"required":false,"descs":{}},"paymentEnterprise":{"enable":true,"required":false,"descs":{}},"buyofferdetailid":{"enable":true,"required":false,"descs":{}},"planDeliverDate":{"enable":true,"required":false,"descs":{},"type":"datetime"},"confirmArriveDate":{"enable":true,"required":false,"descs":{},"type":"date"},"orderDetailId":{"enable":true,"required":false,"descs":{}},"skuId":{"enable":true,"required":false,"descs":{}},"skuValue":{"enable":true,"required":false,"descs":{}},"suppProductUrl":{"enable":true,"required":false,"descs":{}},"customerActualReceivedNum":{"enable":true,"required":false,"descs":{}},"customerAcceptReceivedNum":{"enable":true,"required":false,"descs":{}},"diffCustomerActualReceivedNum":{"enable":true,"required":false,"descs":{}},"diffCustomerAcceptReceivedNum":{"enable":true,"required":false,"descs":{}},"deliveredNum":{"enable":true,"required":false,"descs":{}},"deliveryleftnum":{"enable":true,"required":false,"descs":{}},"nyDatangMaterialCode":{"enable":true,"required":false,"descs":{}}},"params":{"cls":"com.yonyou.cpu.domain.saleorder.SaleOrderDetail"},"rows":[],"select":[],"focus":-1,"pageSize":300,"pageIndex":0,"isChanged":false,"master":"","pageCache":false}}',
                                'compression': 'false',
                                'compressType': '',
                                'parameters': '{"id":"' + str(id) + '"}',
                            },
                            meta={
                                'batchNo': self.batch_no,
                                'order': copy.copy(order),
                            },
                            callback=self.parse_order_item,
                            priority=40,
                            dont_filter=True
                        )
                    else:
                        self.logger.info('异常数据：%s' % order)

            # 列表下一页
            next_page = page + 1
            status = meta.get('status')
            yield scrapy.FormRequest(
                method='POST',
                url=self.api_url,
                formdata={
                    'ctrl': 'portal.MiddlemanPurOrderController',
                    'method': 'loadPurData',
                    'environment': '{"clientAttributes":{}}',
                    'dataTables': '{"middlemanPurOrderDataTable":{"meta":{"id":{"enable":true,"required":false,"descs":{}},"subject":{"enable":true,"required":false,"descs":{}},"orderDesc":{"enable":true,"required":false,"descs":{}},"orderno":{"enable":true,"required":false,"descs":{}},"orderOtherId":{"enable":true,"required":false,"descs":{}},"orderTime":{"enable":true,"required":false,"descs":{},"type":"date"},"corpAccount":{"enable":true,"required":false,"descs":{}},"corpSubAccount":{"enable":true,"required":false,"descs":{}},"supplierName":{"enable":true,"required":false,"descs":{}},"totalMoney":{"enable":true,"required":false,"descs":{}},"orderStatus":{"enable":true,"required":false,"descs":{}},"OrderStatusName":{"enable":true,"required":false,"descs":{}},"gmtCreate":{"enable":true,"required":false,"descs":{},"type":"datetime"},"releaseStart":{"enable":true,"required":false,"descs":{},"type":"datetime"},"releaseEnd":{"enable":true,"required":false,"descs":{},"type":"datetime"},"supEnterpriseName":{"enable":true,"required":false,"descs":{}},"erpProductVersion":{"enable":true,"required":false,"descs":{}},"saleOrderDetailInfo":{"enable":true,"required":false,"descs":{}},"purEnterpriseName":{"enable":true,"required":false,"descs":{}},"deliveryStatus":{"enable":true,"required":false,"descs":{}},"orgName":{"enable":true,"required":false,"descs":{}},"EnterpriseName":{"enable":true,"required":false,"descs":{}},"nyAgreementName":{"enable":true,"required":false,"descs":{}},"nyMiddlemanName":{"enable":true,"required":false,"descs":{}},"nySalesModel":{"enable":true,"required":false,"descs":{}},"enterpriseId":{"enable":true,"required":false,"descs":{}},"field1":{"enable":true,"required":false,"descs":{}}},"params":{"cls":"com.yonyou.cpu.domain.middleman.MiddlemanPurOrder"},"rows":[],"select":[0],"focus":-1,"pageSize":100,"pageIndex":' + str(
                        next_page) + ',"isChanged":false,"master":"","pageCache":false}}',
                    'compression': 'false',
                    'compressType': '',
                    'parameters': '{"billStatus":' + status + ',"pageIndex":' + str(
                        next_page) + ',"pageSize":100,"queryData":{}}',
                },
                meta={
                    'batchNo': self.batch_no,
                    'status': status,
                    'page': next_page,
                },
                callback=self.parse_order,
                errback=self.error_back,
                priority=20,
                dont_filter=True
            )
        else:
            self.logger.info('空列表: page=%s' % page)

    def parse_order_item(self, response):
        meta = response.meta
        order_id = meta.get('order').get('id')
        order_code = meta.get('order').get('orderCode')

        items = parse_order_item(response)
        self.logger.info('明细: id=%s, cnt=%s' % (order_id, len(items)))
        for item in items:
            if item.get('skuId', ''):
                # 商品编号转换
                sp_sku_id = item.get('skuId')
                sp_id = item.get('supplierId')
                real_sku_id = self.converter.convert_id(sp_sku_id, sp_id)
                if real_sku_id:
                    item['skuId'] = real_sku_id
                    yield item
                else:
                    self.logger.info('转码失败: order=%s, order_code=%s, sp_sku_id=%s, sp_id=%s' % (
                        order_id, order_code, sp_sku_id, sp_id))
            else:
                self.logger.info('异常数据: order=%s, order_code=%s' % (order_id, order_code))
